﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AzureStorageLight
{
    internal class StorageCacheManager
    {
        private ConcurrentDictionary<string, CachedItem> CachedRepository = new ConcurrentDictionary<string, CachedItem>();

        public List<StorageItem> GetCachedData(string id)
        {
            CachedItem data;
            if (CachedRepository.TryGetValue(id, out data) && data.Expired > DateTime.Now)
            {
                return ((List<StorageItem>)data.Data);
            }
            return null;
        }

        public StorageItem FindCachedItem(string id)
        {
            foreach (var data in CachedRepository)
            {
                if (data.Value.Expired > DateTime.Now)
                {
                    foreach (var item in data.Value.Data)
                    {
                        if (item.Id == id) return item;
                    }
                }
            }
            return null;
        }

        public void SetCachedData(string id, List<StorageItem> data)
        {
            CachedRepository[id] = new CachedItem(data);
            foreach (var item in CachedRepository.ToList())
            {
                if (item.Value.Expired < DateTime.Now)
                {
                    CachedItem work;
                    CachedRepository.TryRemove(item.Key, out work);
                }
            }
        }
        public void ClearCachedData(string id)
        {
            CachedItem work;
            CachedRepository.TryRemove(id, out work);
        }

        public void AddCachedData(StorageItem item)
        {
            var cache = GetCachedData(item.FolderId);
            if (cache != null)
            {
                cache.Add(item);
            }
        }
        public void RemoveCachedData(StorageItem item)
        {
            var cache = GetCachedData(item.FolderId);
            if (cache != null)
            {
                cache.Remove(item);
            }
        }

    }

}
